package com.dankegongyu.lib.common.util;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import static com.dankegongyu.lib.common.util.GlobalContext.getAppContext;

/**
 * IO工具
 * @author wpq
 * @version 1.0
 */
public final class IOUtil {

    private IOUtil(){
        throw new AssertionError("cannot be instantiated");
    }

    /**
     * 静默关闭流
     * @param closeables e.g. SQLiteDatabase, Cursor, InputStream etc.
     */
    public static void closeQuietly(Closeable... closeables) {
        if (closeables == null)
            return;
        for (Closeable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
//                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 从assets中读取文件内容
     */
    public static String readFromAssets(String fileName) {
        InputStream is = null;
        try {
            is = getAppContext().getAssets().open(fileName);
            return readTextFromSDCard(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeQuietly(is);
        }
        return "";
    }

    /**
     * 从raw中读取内容
     */
    public static String readFromRaw(int rawResId) {
        InputStream is = null;
        try {
            is = GlobalContext.getAppContext().getResources().openRawResource(rawResId);
            return readTextFromSDCard(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 按行读取内容
     *
     * @param is
     * @return
     * @throws Exception
     */
    public static String readTextFromSDCard(InputStream is){
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        //noinspection StringBufferMayBeStringBuilder
        StringBuffer buffer = new StringBuffer("");
        try {
            String next = "";
            while ((next = br.readLine()) != null) {
                buffer.append(next);
    //            buffer.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
            buffer.delete(0, buffer.length());
        } finally {
            closeQuietly(br, isr);
        }
        return buffer.toString().trim();
    }

}
